<?php
namespace Admin\Controller;

use Admin\Controller\CommonController;

/**
 * 内容管理相关模块
 * @author wangdong
 *
 * 带前缀的ACTION为控制权限用的，默认为view_
 * 后缀带_iframe的ACTION是在iframe中加载的，用于统一返回格式
 */
class ContentController extends CommonController
{
    /**
     * 对应权限如下：
     * view 查看 | add 添加 | edit 编辑 | delete 删除 | order 排序
     */
    public function _initialize()
    {
        parent::_initialize();
        //权限判断
        if (session('roleid') != 1 && ACTION_NAME != 'index' && strpos(ACTION_NAME, 'public_') === false) {
            $category_priv_db = M('category_priv');
            $tmp = explode('_', ACTION_NAME);
            $action = $tmp[0];
            if (in_array($action, array('view', 'add', 'edit', 'delete', 'order'))) $action = 'view';

            $catid = intVal(I('get.catid', 0));
            $info = $category_priv_db->where(array('catid' => $catid, 'is_admin' => 1, 'action' => $action))->find();
            if (!$info) {
                //兼容iframe加载返回
                if (IS_GET && (IS_AJAX || strpos(ACTION_NAME, '_iframe') !== false)) {
                    exit('<style type="text/css">body{margin:0;padding:0}</style><div style="padding:6px;font-size:12px">您没有权限操作该项</div>');
                } else {
                    $this->error('您没有权限操作该项');
                }
            }
        }
    }

    /**
     * 内容管理首页
     */
    public function index($catid=0)
    {
        $menu_db = D('Menu');
        $currentpos = $menu_db->currentPos(I('get.menuid'));  //栏目位置
        $this->assign('currentpos', $currentpos);
        $this->assign('catid', $catid);
        $this->display('index');
    }


    /**
     * 右侧栏目
     */
    public function public_right()
    {
        if (S('content_public_right')) {
            $data = S('content_public_right');
        } else {
            $category_db = D('Category');
            $data = $category_db->getCatTree();
            S('content_public_right', $data);
        }
        $this->ajaxReturn($data);
    }

    /**
     * 文章列表
     */
    public function newsList($draw=1,$catid = 0, $start = 0, $length = 10, $search = array(), $sort = 'listorder', $order = 'asc')
    {
//        if (IS_POST) {
        $news_db = M('news');
        //搜索
        if ($catid == 0) {
            $where = array("1=1");
        } else {
            $where = array("`catid` = {$catid}");
        }
        foreach ($search as $k => $v) {
            if (!$v) continue;
            switch ($k) {
                case 'title':
                    $where[] = "`{$k}` like '%{$v}%'";
                    break;
                case 'begin':
                    if (!preg_match("/^\d{4}(-\d{2}){2}$/", $v)) {
                        unset($search[$k]);
                        continue;
                    }
                    if ($search['end'] && $search['end'] < $v) $v = $search['end'];
                    $v = strtotime($v);
                    $where[] = "`inputtime` >= '{$v}'";
                    break;
                case 'end':
                    if (!preg_match("/^\d{4}(-\d{2}){2}$/", $v)) {
                        unset($search[$k]);
                        continue;
                    }
                    if ($search['begin'] && $search['begin'] > $v) $v = $search['begin'];
                    $v = strtotime($v);
                    $where[] = "`inputtime` <= '{$v}'";
                    break;
            }
        }
        $where = implode(' and ', $where);
        $limit = $start . "," . $length;
        $total = $news_db->where($where)->count();
        $order = $sort . ' ' . $order;
        $field = array('id', 'listorder', 'title', 'username', 'FROM_UNIXTIME(updatetime, "%Y-%m-%d %H:%i:%s") as updatetime', 'FROM_UNIXTIME(inputtime, "%Y-%m-%d %H:%i:%s") as inputtime', 'status');
        $list = $total ? $news_db->field($field)->where($where)->order($order)->limit($limit)->select() : array();
//        $data = array('total' => $total, 'rows' => $list);
        $data = array(
            "draw" => $draw,
            "recordsTotal" => $total,
            "recordsFiltered" => $total,
            "data" => $list
        );
        $this->ajaxReturn($data);
    }

    /**
     * 添加文章
     */
    public function add_news_iframe($catid=0,$id=0)
    {
        if (IS_POST) {
            $data = I('post.info', array(), 'trim');
            if (!$data['title'] || !$data['content']) $this->error('请填写必填字段');
            $data['catid'] = $catid;

            //转向链接判断
            if (!isset($data['islink'])) {
                unset($data['url']);
                $data['islink'] = 0;
            }
            //状态
            $data['status'] = isset($data['status']) ? '1' : '0';

            //自动提取描述
            $data['description'] = $data['description'] ? strip_tags($data['description']) : strip_tags($data['content']);
            if ($data['description']) $data['description'] = msubstr(str_replace(array("\n", "\r\n", ' ', '　','...'), '', strip_tags($data['description'])), 0, 100);

            //自动提取缩略图
            if (!$data['thumb']) {
                if (preg_match_all("/(src)=([\"|']?)([^ \"'>]+\.(gif|jpg|jpeg|bmp|png))\\2/i", $data['content'], $matches)) {
                    $data['thumb'] = $matches[3][0];
                }
            }

            $news_db = M('news');
            if($id==0){
                //添加时间
                $data['inputtime'] = time();
                $res = $news_db->add($data);
                $res ? $this->success('操作成功') : $this->error('操作失败');
            }else{//编辑时间
                $data['updatetime'] = time();
                $res = $news_db->where(array('catid' => $catid, 'id' => $id))->save($data);
                $res ? $this->success('操作成功') : $this->error('操作失败');
            }

        } else {
            if($id!=0){
                $news_db = M('news');
                $info = $news_db->where(array('id' => $id))->find();
                $catid = $info['catid'];
                $this->assign('info', $info);
            }
            $this->assign('catid', $catid);
            $this->display('news_add');
        }
    }


    /**
     * 删除文章
     */
    public function delete_news()
    {
        if (IS_POST) {
            $news_db = M('news');
            $ids = I('post.ids', array());
            foreach ($ids as $id) {
                $news_db->where(array('id' => $id))->delete();
            }
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    /**
     * 文章排序
     */
    public function order_news()
    {
        if (IS_POST) {
            $order = I('post.order');
            $id = I('post.id');
            $news_db = M('news');
            $news_db->where(array('id'=>$id))->save(array('listorder'=>$order));
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }


    /**
     * 单页面
     */
    public function page_iframe($catid)
    {
        $page_db = M('page');
        if (IS_POST) {
            $data = I('post.info');
            $data['updatetime'] = time();

            if ($page_db->where(array('catid' => $catid))->find()) {
                $res = $page_db->where(array('catid' => $catid))->save($data);
            } else {
                $data['catid'] = $catid;
                $res = $page_db->add($data);
            }
            $res ? $this->success('操作成功') : $this->error('操作失败');
        } else {
            $info = $page_db->where(array('catid' => $catid))->find();
            $info['content'] = $info['content']; //将上传文件地址转成URL，防止无法显示
            $category_db = D('Category');
            $res = $category_db->where(array('catid' => $catid))->find();
            $this->assign('catname', $res['catname']);
            $this->assign('info', $info);
            $this->assign('catid', $catid);
            $this->display('page');
        }

    }
}